package client;

import command.client.CommandFactoryClient;
import command.client.CreateUserClient;
import command.client.InviteUserToChatClient;
import command.client.LoginUserClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Conversation;
import model.MessageCommunication;
import model.User;

public class Client {

    private ClientSession session;

    public Client() {
    }

    public ClientSession getSession() {
        return session;
    }

    public MessageCommunication createNewUser(User u) {
        CreateUserClient c = (CreateUserClient) CommandFactoryClient.getCommand("createuserclient");
        c.setUser(u);
        session = new ClientSession();
        c.execute(session, false);
        sendMessageToServer("disconnectuserserver");
        return c.getOperationStatus();
    }

    public MessageCommunication loginUser(User u) {
        LoginUserClient c = (LoginUserClient) CommandFactoryClient.getCommand("loginuserclient");
        c.setUserLogin(u);
        session = new ClientSession();
        c.execute(session, false);
        if (c.getOperationStatus().getStatus() && c.getOperationStatus().getStatus() != null) {
            session.start();
        } else {
            sendMessageToServer("disconnectuserserver");
        }
        return c.getOperationStatus();
    }

    public void sendMessageToServer(String message) {
        try {
            session.getObjectOutputStream().writeObject(new MessageCommunication(true, message));
            session.getObjectOutputStream().flush();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE,
                    "Fallo al realizar el envío del mensaje al servidor", ex);
        }

    }

    public void inviteUsersAtConversation(ArrayList<String> userList, String userInvites,
            Conversation newConversation) {
        InviteUserToChatClient command = new InviteUserToChatClient();
        command.setUserList(userList);
        command.setUserInvites(userInvites);
        command.setNewConversation(newConversation);
        command.execute(session, false);
    }
}
